import React,{useState,useRef,useEffect} from 'react'
import type { AtEachMember } from '../chat-input-react/types/index'
import "./style/index.css"

const AtPopover:React.FC<{ visible:boolean;list?:AtEachMember[];confirm:(name:string)=>void}>=(props)=>{
    const {visible=false,list=[],confirm:confirmEmit}=props;
    const [positionStyle,setPositionStyle]=useState<{
        top:number|string;
        left:number|string;
    }>({top:0,left:0})

    // 改变位置样式
    const changePosition = () => {
        
            if(window&&window.getSelection()){
                const sel= window.getSelection() as Selection;
                let range = sel.getRangeAt(0); // 获取当前光标
                let position = range.getBoundingClientRect(); // 获取标签位置
                const {x,y}=position;
                const atPopoverContentHeight=(atPopoverContentRef.current&&atPopoverContentRef.current?.clientHeight)||0
                setPositionStyle({
                    top: y-atPopoverContentHeight + "px",
                    left: x + "px",
                })
            }
    };

    // 容器
    const atPopoverContentRef=useRef(null)

    const handleSelect=(name:string)=>{
        confirmEmit(name)
    }
    const [activeLineNum,setActiveLineNum]=useState(0)
     // 当前选中@
    let activeLine=0

    // 处理键盘上下键长度较长滚动
    useEffect(()=>{
        const current=atPopoverContentRef.current
        if(current){
            const atPopoverLineHeight=document.querySelector('.at-popover-line')?.clientHeight||0
            const maxShowLine=Math.floor(current.clientHeight/atPopoverLineHeight)
            if(activeLineNum>=maxShowLine){
                atPopoverContentRef.current?.scrollTo(0,(activeLineNum-maxShowLine+2)*atPopoverLineHeight)
            }
            else{
                atPopoverContentRef.current?.scrollTo(0,0)
            }
        }
        else{
            atPopoverContentRef.current?.scrollTo(0,0) 
        }
    },[activeLineNum,atPopoverContentRef])

    // @功能上下键切换
    const handleKeyUp = (e) => {
        if (visible) {
            // 下键
            if (e.keyCode === 40) {
                // 处理使用useEffect时，activeLineNum不更新的问题
                activeLine=(Math.min(activeLine+1,list.length-1))
                setActiveLineNum((pre)=>pre<activeLine?pre+1:pre>activeLine?pre-1:pre)
            }
            // 上键 
            else if (e.keyCode === 38) {
                activeLine=(Math.max(activeLine-1,0))
                setActiveLineNum((pre)=>pre<activeLine?pre+1:pre>activeLine?pre-1:pre)
            }
            // 回车键 
            else if (e.keyCode === 13) {
                handleSelect(list[activeLine].name)
            }
        }
    };

    useEffect(()=>{
        const atPopoverContent=atPopoverContentRef.current
        if(atPopoverContent){
            activeLine=0
            setActiveLineNum(0)
            changePosition()
        }
        if(visible){
            document.addEventListener("keyup", handleKeyUp);
            return () => {
                document.removeEventListener('keyup', handleKeyUp);
            };
        }
    },[atPopoverContentRef,list,visible])
    return (
        <>
            {visible&&<div  className="at-popover" id="at-popover" style={positionStyle}>
                <div className="at-popover-content" ref={atPopoverContentRef} key={activeLine}>
                    <ul>
                        {
                            list&&list.length>0&&list.map((item,index)=>{
                               
                                return (
                                    <li className={`${index===activeLineNum?'active':''} at-popover-line`}  onClick={()=>handleSelect(item.name)} key={index}>
                                        {
                                            item.avatar&&<div className="at-popover-line-avatar-wrap"><img src={item.avatar} alt="" className="at-popover-line-avatar" /> </div>
                                        }
                                        <div>{item.name}</div>
                                    </li>
                                )
                            })
                        }
                    </ul>
                </div>
            </div>}
        </>
        
    )
}

export default AtPopover